package com.fer.tankr.controllers;

import org.andengine.engine.camera.Camera;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;

import android.util.Log;

import com.fer.andenginemvc.api.Controller;
import com.fer.tankr.GlobalState;
import com.fer.tankr.MainActivity;
import com.fer.tankr.scenes.LevelsScene;
import com.fer.tankr.scenes.SceneManagerImpl;

public class LevelsController extends Controller<MainActivity> implements IOnMenuItemClickListener{

	int maxLevel = 1;
	
	public LevelsController(MainActivity baseGame, Camera camera) {
		super(new LevelsScene(camera,baseGame.getVertexBufferObjectManager(),baseGame.assetManager),baseGame, camera);
		getScene().setBackgroundEnabled(true);
		getScene().setOnMenuItemClickListener(this);
	}

	@Override
	public void onShow() {
		camera.setChaseEntity(scene);
		if (camera.getHUD()!=null)
		{
			camera.getHUD().detachSelf();
		}
		maxLevel = GlobalState.get().getMaxLevel();
		
		float width = camera.getWidth()/10;
		float height = camera.getHeight()/6;
		float blockWidth = getScene().lBlocks[0].getWidth()/2;
		float blockHeight = getScene().lBlocks[0].getHeight()/2;
		
		for (int i = 0; i < getScene().lBlocks.length; i++) {
			if(i<maxLevel){
				getScene().detachChild(getScene().lBlocks[i]);
				getScene().lBlocks[i] = new SpriteMenuItem(getScene().LBLOCKS[i], baseGame.assetManager.levelImgs[i], baseGame.getVertexBufferObjectManager());
				int col = (i+1)%5 == 1 ? 1 : ((i+1)%5 == 2 ? 3 : ((i+1)%5 == 3 ? 5 : ((i+1)%5 == 4 ? 7 : 9)));
				float x = col*width-blockWidth;				
				int row = i+1 <= 5 ? 1 : (i+1 <= 10 ? 3 : 5);
				float y = row*height-blockHeight;
				getScene().lBlocks[i].setPosition(x, y);
				getScene().addMenuItem(getScene().lBlocks[i]);
			}
		}
	}
	
	public LevelsScene getScene()
	{
		return (LevelsScene)scene;
	}

	@Override
	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
		if (pMenuItem.getID() <= maxLevel){
			int level = pMenuItem.getID();
			GlobalState.get().setCurrentLevel(level);
			Log.d("On LevelsController", "Current level: " + level);
			baseGame.setScene(SceneManagerImpl.GAME);
		}
		else {
			baseGame.vibrate();
		}
		
		return true;
	}

	
}